package com.github.freewu.commons.libs;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.ProgressBar;

public class MyProgressBar extends ProgressBar{

	ProgressListener progressListener;
	Paint paint;
	String text="0%";
	Rect rect;
	float density;
	
	public MyProgressBar(Context context) {
		super(context);
		init(context);
	}
	public MyProgressBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}
	public MyProgressBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public void setProgressListener(ProgressListener progressListener) {
		this.progressListener = progressListener;
	}
	
	void init(Context context){
		rect = new Rect();
		paint = new Paint();
		DisplayMetrics dm=new DisplayMetrics();
		((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		density = dm.density;
		paint.setTextSize(17*density);
	}
	public void setPaint(Paint paint) {
		this.paint = paint;
	}
	@Override
	public synchronized void setProgress(int progress) {
		if (progressListener!=null) {
			this.text = progressListener.setText(progress);
		}else {
			this.text = progress + "%";
		}
		super.setProgress(progress);
		invalidate();
	}
	
	@Override
	protected synchronized void onDraw(Canvas canvas) {
		paint.getTextBounds(text, 0, text.length(), rect);
		int x = (getWidth()/2) - rect.centerX();
		int y = (getHeight()/2) - rect.centerY();
		canvas.drawText(text, x, y, paint);
		super.onDraw(canvas);
	}
	
	public interface ProgressListener {
		public String setText(int progress);
	}
}
